package com.ygsoft.tianlu_mall.controller;

import com.alibaba.druid.util.StringUtils;
import com.aliyun.oss.OSSClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ygsoft.tianlu_mall.pojo.Msg;
import com.ygsoft.tianlu_mall.pojo.Shop;
import com.ygsoft.tianlu_mall.pojo.User;
import com.ygsoft.tianlu_mall.service.LoginConstant;
import com.ygsoft.tianlu_mall.service.ShopService;
import com.ygsoft.tianlu_mall.service.UserService;
import com.ygsoft.tianlu_mall.util.UserRegiste;
import com.ygsoft.tianlu_mall.util.ValidateCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


@Controller
@RequestMapping("mall")
public class userController {
    @Autowired
    UserService userService;

    @Autowired
    ShopService shopService;

    @Autowired
    private OSSClient ossClient;
//    /**
//     * 生成验证码
//     * @param request
//     * @param response
//     * @throws IOException
//     * @ValidateCode.generateTextCode(验证码字符类型,验证码长度,需排除的特殊字符)
//     * @ValidateCode.generateImageCode(文本验证码,图片宽度,图片高度,干扰线的条数,字符的高低位置是否随机,图片颜色,字体颜色,干扰线颜色)
//     */
//    @RequestMapping(value = "validateCode")
//    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String verifyCode = ValidateCode.generateTextCode(ValidateCode.TYPE_NUM_LOWER, 4, null);
//        HttpSession session = request.getSession();
//        session.setAttribute("validateCode", verifyCode);
//        response.setHeader("Access-Token",session.getId());
////        response.setHeader("Cache-Control", "no-cache");
//        System.out.println("生成的验证码="+verifyCode);
////        request.getSession().setAttribute("validateCode", verifyCode);
//        response.setContentType("image/jpeg");
//        BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30, 5, true, Color.WHITE, Color.BLUE, null);
//        ImageIO.write(bim, "JPEG", response.getOutputStream());
////        HashMap<String,Object> result = new HashMap<>();
////        result.put("The code",verifyCode);
////        return Msg.succes().add("result",result);
//    }

    /**
     * 生成验证码
     * @param request
     * @param response
     * @throws IOException
     * @ValidateCode.generateTextCode(验证码字符类型,验证码长度,需排除的特殊字符)
     * @ValidateCode.generateImageCode(文本验证码,图片宽度,图片高度,干扰线的条数,字符的高低位置是否随机,图片颜色,字体颜色,干扰线颜色)
     */
    @RequestMapping(value = "validateCode")
    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-cache");
        String verifyCode = ValidateCode.generateTextCode(ValidateCode.TYPE_NUM_LOWER, 4, null);
        System.out.println("生成的验证码="+verifyCode);
        request.getSession().setAttribute("validateCode", verifyCode);
        response.setContentType("image/jpeg");
        BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30, 5, true, Color.WHITE, Color.BLUE, null);
        ImageIO.write(bim, "JPEG", response.getOutputStream());
//        HashMap<String,Object> result = new HashMap<>();
//        result.put("The code",verifyCode);
//        return Msg.succes().add("result",result);
    }

//    @RequestMapping(value = "/shirologin", method = RequestMethod.POST)
//    @ResponseBody
//   public Msg shirologin(
//            @RequestParam(value = "user_name") String user_name, @RequestParam(value = "user_password")String user_password,
//            HttpServletRequest request,HttpServletResponse response) {
//        Session session = SecurityUtils.getSubject().getSession();
//        String code = (String) session.getAttribute("validateCode");
//        String submitCode = WebUtils.getCleanParam(request, "validateCode");
//        if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code,submitCode.toLowerCase())) {
//            request.setAttribute("LOGIN_ERROR_CODE", LoginConstant.LOGIN_ERROR_CODE_100000);
//            request.setAttribute("LOGIN_ERROR_MESSAGE", LoginConstant.LOGIN_ERROR_MESSAGE_VALIDATECODE);
//            return Msg.fail().add("info","验证码有误");
//        }
//        Subject currentUser = SecurityUtils.getSubject();
////        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user_name, user_password);
//        //未认证登录
//        if (!currentUser.isAuthenticated()) {
//            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user_name, user_password);
//            try {
//                //认证登陆
//                currentUser.login(usernamePasswordToken);
//            } catch (AuthenticationException e) {
//                e.getMessage();
//                e.printStackTrace();
//                System.out.print("登录失败");
//                return Msg.fail();
//            }
//        }
//        User users = userService.findByUserName(user_name);
//        int userid=users.getUser_id();
//        //返回用户的roleid
//        int roleid = userService.getRoleId(userid);
//        //返回用户的shopid
//        int shopid = userService.getshopid(userid);
//        HashMap<String,Object> result = new HashMap<>();
//        result.put("Users",users);
//        result.put("roleid",roleid);
//        result.put("shopid",shopid);
//        return Msg.succes().add("result",result);
//
//    }


    @RequestMapping(value = "/shirologin", method = RequestMethod.POST)
    @ResponseBody
    public Msg shirologin(
            @RequestParam(value = "user_name") String user_name,@RequestParam(value = "user_password")String user_password) {

        Subject currentUser = SecurityUtils.getSubject();
//        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user_name, user_password);
        //未认证登录
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user_name, user_password);

//                UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user_name, EncryptKit.MD5(user_password))
            try {
                //认证登陆
                currentUser.login(usernamePasswordToken);
//                User users = userService.findByUserName(user_name);
            } catch (AuthenticationException e) {
                e.getMessage();
                e.printStackTrace();
                System.out.print("登录失败");
                return Msg.fail();
            }
        }
        User users = userService.findbyusername(user_name);
        int userid=users.getUser_id();
        //返回用户的roleid
        int roleid = userService.getRoleId(userid);
        //返回用户的shopid
//        int shopid = userService.getshopid(userid);
        //返回用户的shop信息
        Shop shop = shopService.getShopById(userid);
        HashMap<String,Object> result = new HashMap<>();
        if(null == shop) {
            result.put("Users",users);
            result.put("roleid",roleid);
            result.put("shopid","用户暂未开铺");
        }else {
            int shopid = shop.getShop_id();
            result.put("Users", users);
            result.put("roleid", roleid);
            result.put("shopid", shopid);
        }
        return Msg.succes().add("result",result);


    }

//    /**
//     * 生成验证码
//     * @param request
//     * @param response
//     * @throws IOException
//     */
//    @RequestMapping(value = "/validateCode")
//    public void validateCode(HttpServletRequest request, HttpServletResponse response)
//            throws IOException {
//        response.setHeader("Cache-Control", "no-cache");
//        String verifyCode = ValidateCode.generateTextCode(ValidateCode.TYPE_NUM_ONLY,4,null);
//        request.getSession().setAttribute("validateCode", verifyCode);
//        response.setContentType("image/jpeg");
//        BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30, 3, true,
//                Color.WHITE, Color.BLACK, null);
//        ImageIO.write(bim, "JPEG", response.getOutputStream());
//    }

    /**
     * 处理用户的注册请求

     */
    @RequestMapping(value = "/userRegister", method = RequestMethod.POST)
    @ResponseBody
    public Msg userRegister(@RequestBody User user)
    {
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-DD HH:mm:ss");
        Date date = new Date();
        user.setUser_regTime(date);
        String user_Name = user.getUser_name();
        String user_password = user.getUser_password();
        String[] saltAndCiphertext = UserRegiste.encryptPassword(user_password);
        user.setSalt(saltAndCiphertext[0]);
        user.setUser_password(saltAndCiphertext[1]);
        userService.add(user);
        User user1 = userService.findbyusername(user_Name);
        int userid = user1.getUser_id();
        userService.addRole(userid);
        return Msg.succes();
    }
    /*
    * shiro更改用户密码
    *
    * */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    @ResponseBody
    public Msg updatePasswor(@RequestParam(value = "user_id") int user_id,
                              @RequestParam(value = "oldPassWord")String oldPassWord,
                              @RequestParam(value = "user_password")String user_password,
                              @RequestParam(value = "cfgPwd")String cfgPwd){
        //从数据库获取的密码值
        String dataBaseOldPassword = userService.selectSystemUserPassword(user_id);
        System.out.println("dataBaseOldPassword="+dataBaseOldPassword);

        //从页面传过来的旧密码值（要先把生成原来的密码的盐取出来先）
        //取盐
        String salt = userService.getOldSalt(user_id);
        String pageReturnOldPassword = new Md5Hash(oldPassWord,salt,1024).toString(); //生成的密文
        System.out.println("pageReturnOldPassword="+pageReturnOldPassword);

        if(!dataBaseOldPassword.equals(pageReturnOldPassword)){
            return Msg.fail().add("info","填写的旧密码不正确");
        }

        //如果输入的旧密码和数据库一致，则将用户传进来的新密码，修改密码
        String[] saltAndCiphertext = UserRegiste.encryptPassword(user_password);
        String newSalt = saltAndCiphertext[0];
        userService.setNewSalt(user_id , newSalt);
        String newUser_password = saltAndCiphertext[1];
        userService.setNewPassword(user_id, newUser_password);

        return Msg.succes();
    }

//    用户名的重复性校验
    @RequestMapping(value = "/checkUser",method = RequestMethod.GET)
    @ResponseBody
        public Msg checkUser(@RequestParam(value = "user_name") String user_name){
        List<User> users = userService.checkUser(user_name);
        if(users.isEmpty()){
            return Msg.succes();
        }else{
            return Msg.fail();
        }
    }


  //用户上传头像到阿里云并保存链接到数据库
    @RequestMapping(value = "/setUsersTitle",method = RequestMethod.POST)
    @ResponseBody
    public Msg setUsersTitle(@RequestParam MultipartFile user_pic, @RequestParam int user_id){
        try {
            String bucketName = "xdeer-mall";
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            //构建上传目录
            String user_name = userService.getUserName(user_id);
            String folder = user_name + "/";
            //文件上传到阿里云
            String titleName = folder + user_pic.getOriginalFilename();
            try {
                ossClient.putObject(bucketName,titleName,user_pic.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            URL titleUrl  =ossClient.generatePresignedUrl(bucketName,titleName,expiration);
            userService.saveUsersTitleUrl(user_id,titleUrl.toString());
            String picUrl = userService.getUsersTieleUrl(user_id);

            return Msg.succes().add("头像地址",picUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

//    public Msg updatePassword(@RequestParam(value = "user_phone") String user_phone,
//                              @RequestParam(value = "oldpassword")String oldpassword,
//                              @RequestParam(value = "user_password")String user_password,
//                              @RequestParam(value = "cfgPwd")String cfgPwd){
//
//        userService.updatePassword(user_phone,oldpassword,user_password,cfgPwd);
//
//        return Msg.succes();
//    }

    //查询员工ALL
    @RequestMapping(value = "/Users",method = RequestMethod.GET)
    @ResponseBody
    public Msg getUsersWithJson(
            @RequestParam(value = "pn",defaultValue = "1")Integer pn,
            @RequestParam Integer pageSize) {
        PageHelper.startPage(pn,pageSize);
        List<User> users = userService.getAll();
        PageInfo page = new PageInfo(users,5);
        return  Msg.succes().add("pageInfo",page);
    }

    //模糊搜索员工by phone
    @RequestMapping(value = "/searchUser",method = RequestMethod.GET)
    @ResponseBody
    public Msg searchUser(
            @RequestParam(value = "user_phone") String user_phone,@RequestParam(value = "pn",defaultValue = "1")Integer pn,
            @RequestParam Integer pageSize){
        if (user_phone.length()!=0){
            PageHelper.startPage(pn,pageSize);
            List<User> usersList = userService.getUsersByLike(user_phone);
            PageInfo page = new PageInfo(usersList,5);
            return  Msg.succes().add("pageInfo",page);
        }else {
            String message = "请输入关键词";
            return Msg.fail().add("message",message);
        }


    }
    //通过电话搜索用户
    @RequestMapping(value = "/searchUserByphone",method = RequestMethod.GET)
    @ResponseBody
    public Msg searchUserByphone(@RequestParam(value = "user_phone") String user_phone){
        List<User> userList = userService.getUsersByPhone(user_phone);
        return  Msg.succes().add("User",userList);
    }




    /**
     * 用户保存
     */
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveUserWithJson(@RequestBody User user){
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-DD HH:mm:ss");
        Date date = new Date();
        user.setUser_regTime(date);
        userService.saveUser(user);
        return Msg.succes();

        }
        //根据id删除员工
        @ResponseBody
        @RequestMapping(value = "/deleteUser/{id}",method = RequestMethod.DELETE)
        public Msg deleteUserById(@PathVariable("id")Integer id){
        userService.deleteByPrimaryKey(id);
        return Msg.succes();
        }
        //批量删除员工
        @RequestMapping(value = "/deletemoreUsers",method = RequestMethod.DELETE)
        @ResponseBody
        public Msg deletemoreUsers(@RequestParam List<Integer> user_idList){
            try {
                for (int user_id:user_idList) {
                    userService.deleteByPrimaryKey(user_id);
                }
                return Msg.succes();
            } catch (Exception e) {
                e.printStackTrace();
                return Msg.fail();
            }
        }
    //员工数据更新
    @RequestMapping(value = "/updateUser/{user_id}",method = RequestMethod.PUT)
    @ResponseBody
    public Msg updateUserById(@RequestBody User user){
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-DD HH:mm:ss");
        Date date = new Date();
        user.setUser_regTime(date);
        userService.updateUser(user);
        return Msg.succes();
        }

        //根据id显示个人信息
    @RequestMapping(value = "/DetailById",method = RequestMethod.GET)
    @ResponseBody
    public Msg getDetailById(@RequestParam(value = "user_id") int user_id){
        List<User> users = userService.getDetailById(user_id);
        Shop shop = shopService.getShopById(user_id);
        HashMap<String,Object> result = new HashMap<>();
        if(null == shop) {
            result.put("Users",users);
            result.put("shopid","用户暂未开铺");
        }else {
            int shopid = shop.getShop_id();
            result.put("Users", users);
            result.put("shopid", shopid);
        }
        return Msg.succes().add("result",result);
    }

    @RequestMapping(value = "/xxx",method = RequestMethod.GET)
    @ResponseBody
    public Msg xxx(@RequestParam(value = "name") String name){
        Set<String> roles = userService.findRoles(name);
        HashMap<String,Object> result = new HashMap<>();
        result.put("roles",roles);
        return Msg.succes().add("result",result);
    }
    }


